//
//  AppDelegate.m
//  一点互助
//
//  Created by 张泊秋 on 16/8/19.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "AppDelegate.h"
#import "HelpTabBarController.h"
#import "ResponseManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "BuddyInfoManager.h"
#import "UserState.h"
#import "EaseUI.h"

@interface AppDelegate ()<EMContactManagerDelegate,EMChatManagerDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    HelpTabBarController *tabbar = [[HelpTabBarController alloc]init];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = tabbar;
    [self.window makeKeyAndVisible];
    //1.1
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge categories:nil];
    [application registerUserNotificationSettings:setting];
    //1.2注册远程推送服务
    [application registerForRemoteNotifications];
    //app处于关闭状态接收到推送通知
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginStateChanged:) name:@"loginStateChanged" object:nil];
    EMOptions *options = [EMOptions optionsWithAppkey:@"fiona#amutualassistance"];
     [[EMClient sharedClient]initializeSDKWithOptions:options];
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];

    //移除好友回调
//    [[EMClient sharedClient].contactManager removeDelegate:self];
//    [[EaseSDKHelper shareHelper] easemobApplication:application
//                      didFinishLaunchingWithOptions:launchOptions
//                                             appkey:@"fiona#amutualassistance"
//                                       apnsCertName:nil
//                                        otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    [[EaseSDKHelper shareHelper] hyphenateApplication:application didFinishLaunchingWithOptions:launchOptions appkey:@"fiona#amutualassistance" apnsCertName:nil otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
      return YES;
}

-(void)didReceiveAddedFromUsername:(NSString *)aUsername{
    PLLOG(@"%@",aUsername);
}
-(void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername message:(NSString *)aMessage{
    UserState *user = [[UserState alloc]init];
    NSDictionary *dic = @{@"username":aUsername,@"message":aMessage};
    [user.invitationArr addObject:dic];
    PLLOG(@"%@,%@",aUsername,aMessage);
}
-(void)loginStateChanged:(NSNotification *)notification{
    BOOL isLogin = [notification.object boolValue];
    if (isLogin) {
//        获取好友信息并存储到本地
        [[BuddyInfoManager shareBuddyInfoManager] getAllBuddyListFromServerCompletion:nil];
    }else{
        //清空好友信息
    }
}
-(void)messagesDidReceive:(NSArray *)aMessages{
    PLLOG(@"%@",aMessages);
    UserState *user = [[UserState alloc]init];
    user.messageArr = aMessages;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//注册远程推送服务成功后会返回devicetoken
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

}
//接受推送消息：iOS7之前：
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

}
//iOS7之后：(进程运行中)
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    completionHandler(UIBackgroundFetchResultNewData);
}
//注册失败
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    PLLOG(@"%@",error.localizedDescription);
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    [self handlalipayResult:url];
    return YES;
    
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    [self handlalipayResult:url];
    return YES;
    
}

- (void)handlalipayResult:(NSURL *)url {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //从支付宝客户端跳转至客户App
        
        //获取支付宝返回结果 并处理
        [[AlipaySDK defaultService]processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"支付宝返回结果:%@",resultDic);
        }];
        
    }
    
}

@end
